package action.article;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.ArticleManager;
import service.impl.ArticleManagerImpl;

public class ListArticleByTypeAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ArticleManager am = new ArticleManagerImpl();
		int articleType_Id;
		String articleTypeIdStr=request.getParameter("articleTypeId");
		System.out.println("-------------"+articleTypeIdStr);
		if(articleTypeIdStr==null || articleTypeIdStr.trim().equals("")){
			articleType_Id=-1;
		}
		try{
			articleType_Id=Integer.parseInt(articleTypeIdStr.trim());
		}catch(Exception e){
			articleType_Id=-1;
		}
		if(articleType_Id==-1){
			String atid=(String) request.getAttribute("articleTypeId");
			if(atid==null || atid.trim().equals("")){
				articleType_Id=1;
			}else{
				articleType_Id=Integer.parseInt(atid.trim());
			}
		}
		int articleCount=am.getArticleCountByType(articleType_Id);
		int pageCount=am.getPageCountByType(articleCount, am.ARTICLE_PAGE_SIZE);
		int pageNo;
		String pageNoStr=request.getParameter("pageNo");
		if(pageNoStr==null || pageNoStr.trim().equals("")){
			pageNo=1;
		}
		try{
			pageNo=Integer.parseInt(pageNoStr.trim());
		}catch(Exception e){
			pageNo=1;
		}
		if(pageNo>pageCount){
			pageNo=pageCount;
		}
		request.setAttribute("no" , (pageNo-1)*am.ARTICLE_PAGE_SIZE);
		request.setAttribute("pageCount", pageCount);
		request.setAttribute("currentPage", pageNo);
		request.setAttribute("articleList", am.getAllArticleByTypeByPage(articleType_Id,pageNo));
		request.setAttribute("articleType", am.getArticleType(articleType_Id));
		request.setAttribute("msg", am.getMsg());
		request.getSession().setAttribute("PRE_URL",request.getHeader("Referer"));
		return mapping.findForward("listArticleByType");
	}

}
